/*
 * WebServer.h
 *
 *  Created on: Jul 9, 2024
 *      Author: root
 */

#ifndef BSP_SERVER_WEBSERVER_H_
#define BSP_SERVER_WEBSERVER_H_
#include "all_header.h"

namespace bsp {

class WebServer {
public:
	enum class Event : uint8_t {
		MODIFY_SD_EPOLL = 0, CLOSE_CLIENT,
	};

	typedef struct ServerEvent {
		int id;
		int sd;
		int flag;
	} ServerEvent;

	WebServer(const char *ip, uint16_t port);
	virtual ~WebServer();

	void open();
	void start();
	void close();
	static void test1();

	void setEpoll(Epoller *p) {
		epoll = p;
	}
	void setTimer(HashTimer *tm) {
		timer = tm;
	}
	void setThreadPool(ThreadPool *p) {
		thd_pool = p;
	}

	void setLocalSock(LocalSocket *s) {
		sock = s;
	}

	void pubModifySdEpollEvent(int sd, int flag) {
		ServerEvent evt = { (int) Event::MODIFY_SD_EPOLL, sd, flag };
		ASSERT(sock->write((const char* )&evt, sizeof(evt)) == sizeof(evt), "");
	}
	void pubClosClientEvent(int sd) {
		ServerEvent evt = { (int) Event::CLOSE_CLIENT, sd, 0 };
		ASSERT(sock->write((const char* )&evt, sizeof(evt)) == sizeof(evt), "");
	}

private:
	std::string ip;
	uint16_t port;
	bool quit;

	int sd;
	int client_timeout;
	int cur_max_size;
	std::unordered_set<int> ids;
	Epoller *epoll;
	HashTimer *timer;
	ThreadPool *thd_pool;
	LocalSocket *sock;
	std::unordered_set<int> client_id_sets;
	std::unordered_map<int, HttpConnection> http_conns;

	void socketInit();

	void dealListen();

	static void clientRead(WebServer *server, HttpConnection *conn);

	static void clientWrite(WebServer *server, HttpConnection *conn);

	static void timeoutCloseClient(WebServer *server, int fd);

	void addClient(int fd);
	void closeClient(int fd);
	void modifyClient(int fd, int pollflag);

	void processLocalSockEvent();

}
;

} /* namespace bsp */

#endif /* BSP_SERVER_WEBSERVER_H_ */
